package com.wangshb.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangshb.upms.core.utils.AssertUtil;
import com.wangshb.upms.core.tree.TreeNode;
import com.wangshb.upms.entity.UpmsUserRole;
import com.wangshb.upms.mapper.UpmsUserRoleMapper;
import com.wangshb.upms.service.UpmsRoleService;
import com.wangshb.upms.service.UpmsUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class UpmsUserRoleServiceImpl extends ServiceImpl<UpmsUserRoleMapper, UpmsUserRole> implements UpmsUserRoleService {

    @Resource
    private UpmsUserRoleMapper upmsUserRoleMapper;

    @Autowired
    private UpmsRoleService upmsRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void allocateRoles(Long userId, List<Long> roleIdList) {

        Collection<Long> addRoleIdList = null;
        Collection<Long> deleteRoleIdList = null;

        AssertUtil.isTrue(CollectionUtils.isNotEmpty(roleIdList), "分配的角色不能为空！");

        // 查询已经拥有的权限
        QueryWrapper<UpmsUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("upms_user_id", userId);
        List<UpmsUserRole> dbUpmsUserRoles = this.upmsUserRoleMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(dbUpmsUserRoles)) {

            Set<Long> hadRoleIdList = dbUpmsUserRoles.stream().map(UpmsUserRole::getUpmsRoleId).collect(Collectors.toSet());

            // 移除已经存在的角色
            addRoleIdList = CollectionUtils.removeAll(roleIdList, hadRoleIdList);
            deleteRoleIdList = CollectionUtils.removeAll(hadRoleIdList, roleIdList);

            if (CollectionUtils.isEmpty(addRoleIdList)) {
                log.warn("用户{} - 分配角色 - 无新增角色!", userId);
            }

            if (CollectionUtils.isEmpty(deleteRoleIdList)) {
                log.warn("用户{} - 分配角色 - 无删除角色!", userId);
            }
        }
        else {
            addRoleIdList = roleIdList;
        }

        // 删除
        if (CollectionUtils.isNotEmpty(deleteRoleIdList)) {
            UpdateWrapper<UpmsUserRole> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("upms_role_id", deleteRoleIdList);
            this.upmsUserRoleMapper.delete(updateWrapper);
        }

        // 新增
        List<UpmsUserRole> saveUpmsUserRole = new ArrayList<>(roleIdList.size());
        if (CollectionUtils.isNotEmpty(addRoleIdList)) {
            addRoleIdList.stream().forEach(roleId -> {
                saveUpmsUserRole.add(UpmsUserRole.builder().upmsUserId(userId).upmsRoleId(roleId).build());
            });
            // 批量插入
            super.saveBatch(saveUpmsUserRole, saveUpmsUserRole.size());
        }
    }


    @Override
    public List<Long> listRoleByUserId(Long userId) {

        // 查询已经拥有的权限
        QueryWrapper<UpmsUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("upms_user_id", userId).orderByAsc("id");
        List<UpmsUserRole> dbUpmsUserRoles = this.upmsUserRoleMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(dbUpmsUserRoles)) {
            return dbUpmsUserRoles.stream().map(UpmsUserRole::getUpmsRoleId).collect(Collectors.toList());
        }

        return Collections.emptyList();
    }
}
